package com.applet.message.problem.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;

import com.applet.common.annotation.Anonymous;
import com.applet.common.core.domain.model.LoginUser;
import com.applet.common.core.redis.RedisCache;
import com.applet.common.utils.SecurityUtils;
import com.applet.common.utils.file.AliyunOssUploadUtils;
import com.applet.message.problem.domain.ProblemImage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.applet.common.annotation.Log;
import com.applet.common.core.controller.BaseController;
import com.applet.common.core.domain.AjaxResult;
import com.applet.common.enums.BusinessType;
import com.applet.message.problem.domain.Problem;
import com.applet.message.problem.service.IProblemService;
import com.applet.common.utils.poi.ExcelUtil;
import com.applet.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 问题反馈处理Controller
 *
 * @author ruoyi
 * @date 2024-09-26
 */
@Api(tags = "问题反馈")
@RestController
@RequestMapping("/message/problem")
public class ProblemController extends BaseController {
    @Autowired
    private IProblemService problemService;

    @Autowired
    private AliyunOssUploadUtils aliOssUtil;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询问题反馈处理列表
     */
//    @PreAuthorize("@ss.hasPermi('message:problem:list')")
//    @Anonymous
    @ApiOperation(value = "查询问题反馈列表")
    @GetMapping("/list")
    public TableDataInfo list(Problem problem) {
        startPage();
        List<Problem> list = problemService.selectProblemList(problem);
        return getDataTable(list);
    }
    @GetMapping("/list/user")
    public TableDataInfo userList(Problem problem) {
        startPage();
        List<Problem> list = problemService.selectUserProblemList(problem);
        return getDataTable(list);
    }

    /**
     * 图片上传
     */
    @ApiOperation(value = "图片上传")
    @PostMapping("/image")
    public AjaxResult uploadImage(@RequestParam("problemImage") MultipartFile file,@RequestParam("userId") Long userId) {
        if (!file.isEmpty()) {
//            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            try {
                //获取原始文件名
                String originName = file.getOriginalFilename();
                //截取原始文件名后缀 abc.png
                String suffix = null;
                if (originName != null) {
                    suffix = originName.substring(originName.lastIndexOf("."));
                }
                //构造新文件名称
                String newName = UUID.randomUUID() + suffix;
                String url = aliOssUtil.upload(file.getBytes(), newName);
                AjaxResult ajax = AjaxResult.success();
                //将图片路径存入缓存
                String key = "image_" + userId;
                //先判断此数据是否已经存在
                if (redisCache.hasKey(key)) {//存在，先取出在存入
                    redisCache.getCacheList(key).add(url);
                } else {//不存在，就存入
                    List<String> urlList = new ArrayList<>();
                    urlList.add(url);
                    redisCache.setCacheList(key, urlList);
                    //设置过期时间为10分钟
                    redisCache.expire(key, 60 * 10);
                }
                ajax.put("imgUrl", url);
                return ajax;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return error("图片上传失败,请重试");
    }

    /**
     * 导出问题反馈处理列表
     */
//    @PreAuthorize("@ss.hasPermi('message:problem:export')")
    @Log(title = "问题反馈处理", businessType = BusinessType.EXPORT)
    @ApiOperation(value = "导出问题反馈列表")
    @PostMapping("/export")
    public void export(HttpServletResponse response, Problem problem) {
        List<Problem> list = problemService.selectProblemList(problem);
        ExcelUtil<Problem> util = new ExcelUtil<Problem>(Problem.class);
        util.exportExcel(response, list, "问题反馈处理数据");
    }

    /**
     * 获取问题反馈处理详细信息
     */
//    @PreAuthorize("@ss.hasPermi('message:problem:query')")
    @ApiOperation(value = "获取问题反馈详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(problemService.selectProblemById(id));
    }

    /**
     * 新增问题反馈处理
     */
//    @PreAuthorize("@ss.hasPermi('message:problem:add')")
    @Log(title = "问题反馈处理", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增问题反馈")
    @PostMapping
    public AjaxResult add(@RequestBody Problem problem) {
        String key = "image_" + SecurityUtils.getUserId();
        //判断redis中是否有数据，实则就是看用户有没有上传图片
        if (redisCache.hasKey(key)) {
            List<String> urlList = redisCache.getCacheList(key);
            List<ProblemImage> problemImageList = new ArrayList<>();
            for (String s : urlList) {
                problemImageList.add(new ProblemImage(s));
            }
            problem.setProblemImageList(problemImageList);
            //删除数据
            redisCache.deleteObject(key);
        }
        return toAjax(problemService.insertProblem(problem));
    }

    /**
     * 修改问题反馈处理
     */
//    @PreAuthorize("@ss.hasPermi('message:problem:edit')")
    @Log(title = "问题反馈处理", businessType = BusinessType.UPDATE)
    @ApiOperation(value = "修改问题反馈")
    @PutMapping
    public AjaxResult edit(@RequestBody Problem problem) {
        return toAjax(problemService.updateProblem(problem));
    }

    /**
     * 删除问题反馈处理
     */
//    @PreAuthorize("@ss.hasPermi('message:problem:remove')")
    @Log(title = "问题反馈处理", businessType = BusinessType.DELETE)
    @ApiOperation(value = "删除问题反馈")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(problemService.deleteProblemByIds(ids));
    }
}
